﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Data;

namespace SEP.Admin
{
    public partial class ServiceReportJobCreator : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                //postback
            }
            else
            {
                //not a postback
                BindData();

                if(Request.QueryString["constituentID"] != null)
                {
                    Guid constituentID = Guid.Empty;

                    if(Guid.TryParse(Request.QueryString["constituentID"], out constituentID))
                    {
                        Constituent c = new Constituent(constituentID);

                        if(c != null)
                        {
                            txtLocationFacility.Text = c.Name;

                            if(c.PrimaryContact != null)
                            {
                                txtLocationContact.Text = c.PrimaryContact.Name;
                            }

                            if(c.Address != null)
                            {
                                txtLocationCity.Text = c.Address.City;
                                txtLocationStreet.Text = c.Address.AddressBlock;
                                txtLocationZip.Text = c.Address.PostCode;

                                if(c.Address.State != null)
                                {
                                    ddlLocationState.SelectedValue = c.Address.State.ID.ToString();
                                }
                            }

                            if(c.Phone != null)
                            {
                                txtLocationPhone.Text = c.Phone.Number;
                                txtLocationExtension.Text = c.Phone.Extension;
                            }

                            if(c.EmailAddress != null)
                            {
                                txtLocationEmail.Text = c.EmailAddress.EmailAddress;
                            }

                            try
                            {
                                txtLocationFax.Text = c.Phones.First(x => x.PhoneTypeAsString.Equals("Fax")).Number;
                            }
                            catch { }

                            //bill to
                            txtBillToFacility.Text = c.Name;

                            if (c.PrimaryContact != null)
                            {
                                txtBillToContact.Text = c.PrimaryContact.Name;
                            }

                            if (c.Address != null)
                            {
                                txtBillToCity.Text = c.Address.City;
                                txtBillToStreet.Text = c.Address.AddressBlock;
                                txtBillToZip.Text = c.Address.PostCode;

                                if (c.Address.State != null)
                                {
                                    ddlBillToState.SelectedValue = c.Address.State.ID.ToString();
                                }
                            }

                            if (c.Phone != null)
                            {
                                txtBillToPhone.Text = c.Phone.Number;
                                txtBillToExtension.Text = c.Phone.Extension;
                            }

                            if (c.EmailAddress != null)
                            {
                                txtBillToEmail.Text = c.EmailAddress.EmailAddress;
                            }

                            try
                            {
                                txtBillToFax.Text = c.Phones.First(x => x.PhoneTypeAsString.Equals("Fax")).Number;
                            }
                            catch { }                          
                        }
                    }
                }
            }
        }

        private void BindData()
        {
            List<State> states = new State().GetAll();
            Common.Utility.BindDropDownList<State>(ddlLocationState, states, "ABBREVIATION", "ID");
            Common.Utility.BindDropDownList<State>(ddlBillToState, states, "ABBREVIATION", "ID");

            ddlLocationState.SelectedValue = "00000000-0000-0000-0000-000000000000"; 
            ddlBillToState.SelectedValue = "00000000-0000-0000-0000-000000000000";
            
            BindSearchGridView(grvLocationSearch, Constituent.SearchAll);
                        
            string date = DateTime.Now.ToString();
            txtDate.Text = date.Substring(0, date.IndexOf(" "));
        }

        private void BindSearchGridView(GridView grv, Func<DataTable> searchAllMethod)
        {
            string searchDataTable = grv.ID + "SEARCHDATATABLE";

            DataTable dt = (DataTable)Session[searchDataTable];

            if (dt == null)
            {
                dt = searchAllMethod();
                Session[searchDataTable] = dt;
            }

            grv.DataSource = dt;
            grv.DataBind();
        }

        protected void grvLocationSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            PageIndexChanging(grvLocationSearch, sender, e);
        }
        
        private void PageIndexChanging(GridView grv, object sender, GridViewPageEventArgs e)
        {
            string searchDataTableLocation = grv.ID + "SEARCHDATATABLE";
            string filteredDataTableLocation = grv.ID + "FILTEREDDATATABLE";

            DataTable dt = Session[searchDataTableLocation] as DataTable;

            if (Session[filteredDataTableLocation] != null)
            {
                dt = Session[filteredDataTableLocation] as DataTable;
            }

            grv.DataSource = dt;
            grv.PageIndex = e.NewPageIndex;
            grv.DataBind();
        }

        protected void grvLocationSearch_OnSorting(object sender, GridViewSortEventArgs e)
        {
            OnSorting(e, grvLocationSearch);
        }

        private void OnSorting(GridViewSortEventArgs e, GridView grv) 
        {
            string searchDataTableLocation = grv.ID + "SEARCHDATATABLE";
            string filteredDataTableLocation = grv.ID + "FILTEREDDATATABLE";

            DataTable dt = Session[searchDataTableLocation] as DataTable;

            if (Session[filteredDataTableLocation] != null)
            {
                dt = Session[filteredDataTableLocation] as DataTable;
            }

            if (dt != null)
            {
                //Sort the data.
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression, grv.ID);
                grv.DataSource = dt;
                grv.DataBind();

                Session[searchDataTableLocation] = dt;
                Session[filteredDataTableLocation] = dt;
            }            
        }

        protected void grvLocationSearch_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = 0;

            if (int.TryParse(e.CommandArgument.ToString(), out index) && !e.CommandName.Equals("Sort") && !e.CommandName.Equals("Page"))
            {
                GridViewRow selectedRow = grvLocationSearch.Rows[index];

                if (selectedRow != null)
                {
                    string val = ((HiddenField)selectedRow.FindControl("hidID")).Value;

                    if (!string.IsNullOrWhiteSpace(val))
                    {
                        Guid id = new Guid();

                        if (Guid.TryParse(val, out id))
                        {
                            string searchDataTable = grvLocationSearch.ID + "SEARCHDATATABLE";

                            DataTable dt = (DataTable)Session[searchDataTable];

                            if (dt != null)
                            {
                                foreach (DataRow row in dt.Rows)
                                {
                                    string temp = row["ID"].ToString();

                                    if (id.ToString().Equals(temp))
                                    {
                                        string name = row["NAME"].ToString();
                                        string street = row["STREET"].ToString();
                                        string city = row["CITY"].ToString();
                                        string postcode = row["POSTCODE"].ToString();
                                        string state = row["STATE"].ToString();
                                        string phone = row["PHONE"].ToString();
                                        string fax = row["FAX"].ToString();
                                        string emailaddress = row["EMAILADDRESS"].ToString();
                                        string contact = row["CONTACT"].ToString();

                                        if (e.CommandName.Equals("LOCATION"))
                                        {
                                            txtLocationFacility.Text = name;
                                            txtLocationStreet.Text = street;
                                            txtLocationCity.Text = city;
                                            txtLocationZip.Text = postcode;

                                            ListItem item = ddlLocationState.Items.FindByText(state);

                                            if (item != null)
                                            {
                                                ddlLocationState.SelectedValue = item.Value;
                                            }

                                            txtLocationPhone.Text = phone;
                                            txtLocationFax.Text = fax;
                                            txtLocationEmail.Text = emailaddress;
                                            txtLocationContact.Text = contact;
                                        }
                                        else if (e.CommandName.Equals("BILLTO"))
                                        {
                                            txtBillToFacility.Text = name;
                                            txtBillToStreet.Text = street;
                                            txtBillToCity.Text = city;
                                            txtBillToZip.Text = postcode;

                                            ListItem item = ddlBillToState.Items.FindByText(state);

                                            if (item != null)
                                            {
                                                ddlBillToState.SelectedValue = item.Value;
                                            }

                                            txtBillToPhone.Text = phone;
                                            txtBillToFax.Text = fax;
                                            txtBillToEmail.Text = emailaddress;
                                            txtBillToContact.Text = contact;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //else if(e.CommandName.Equals("Sort"))
            //{
            //    OnSorting(new GridViewSortEventArgs(e.CommandArgument.ToString(), SortDirection.Ascending), grvLocationSearch);
            //}
            //else if(e.CommandName.Equals("Page"))
            //{
            //    var pageIndex = grvLocationSearch.PageIndex;

            //    if(e.CommandArgument.Equals("Next"))
            //    {
            //        pageIndex += 1;
            //    }
            //    else
            //    {
            //        pageIndex -= 1;
            //    }   

            //    PageIndexChanging(grvLocationSearch, new GridViewPageEventArgs(pageIndex));
            //}
        }
        
        private string GetSortDirection(string column, string gridViewName)
        {
            string sortExpressionName = gridViewName + "SortExpression";
            string sortDirectionName = gridViewName + "SortDirection";

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = Session[sortExpressionName] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = Session[sortDirectionName] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            Session[sortDirectionName] = sortDirection;
            Session[sortExpressionName] = column;

            return sortDirection;
        }

        protected void btnLocationSubmit_Click(object sender, EventArgs e)
        {
            string text = txtLocationSearch.Text;
            string searchString = "Name like '%" + text + "%' or Contact like '%" + text + "%'";

            SearchGridView(grvLocationSearch, searchString);
        }

        private void SearchGridView(GridView grv, string searchCriteria)
        {
            string searchDataTable = grv.ID + "SEARCHDATATABLE";

            if (!string.IsNullOrWhiteSpace(searchCriteria))
            {
                string filteredDataTable = grv.ID + "FILTEREDDATATABLE";

                DataTable dt = Session[searchDataTable] as DataTable;

                if (dt != null)
                {
                    DataRow[] rows = dt.Select(searchCriteria);
                    DataTable filtered = dt.Copy();

                    filtered.Rows.Clear();

                    foreach (DataRow r in rows)
                    {
                        filtered.ImportRow(r);
                    }

                    Session[filteredDataTable] = filtered;

                    grv.DataSource = filtered;
                    grv.DataBind();
                }
            }
            else
            {
                grv.DataSource = searchDataTable;
                grv.DataBind();
            }
        }
        
        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            Job job = null;

            try
            {
                job = GetCurrentJob();
                job.Create();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Visible = true;
            }

            if (job.ID != Guid.Empty)
            {
                //the job was created successfully now lets send to the service report bank
                Response.Redirect(string.Format("~/Admin/ServiceReportView.aspx?jobid={0}", job.ID));
            }
        }

        private Job GetCurrentJob()
        {
            Job job = new Job();

            //job name
            job.Description = txtJobName.Text;

            //job date
            job.UserDate = Convert.ToDateTime(txtDate.Text);

            //start location
            Constituent location = new Constituent();
            location.Name = txtLocationFacility.Text;

            //contact
            Constituent contact = new Constituent();
            contact.Name = txtLocationContact.Text;
            location.PrimaryContact = contact;

            //state
            State s = new State();
            s.ID = new Guid(ddlLocationState.SelectedItem.Value);
            s.Abbreviation = (string.IsNullOrWhiteSpace(ddlLocationState.SelectedItem.Text) ? string.Empty : ddlLocationState.SelectedItem.Text);

            //address
            Address address = new Address();
            address.AddressBlock = txtLocationStreet.Text;
            address.City = txtLocationCity.Text;
            address.PostCode = txtLocationZip.Text;
            address.State = s;

            location.Address = address;

            //phone number
            Phone phone = new Phone();
            phone.Number = txtLocationPhone.Text;
            phone.Extension = txtLocationExtension.Text;

            location.Phone = phone;

            //fax            
            phone = new Phone();
            phone.Number = txtLocationFax.Text;

            PhoneType phoneType = new PhoneType();
            phoneType.Description = "Fax";

            phone.PhoneType = phoneType;
            location.Phones.Add(phone);

            //email            
            Email email = new Email();
            email.EmailAddress = txtLocationEmail.Text;

            location.EmailAddress = email;

            job.Location = location;
            //end location

            //start bill to
            Constituent billto = new Constituent();

            billto.Name = txtBillToFacility.Text;

            //contact
            contact = new Constituent();
            contact.Name = txtBillToContact.Text;
            billto.PrimaryContact = contact;


            //state
            s = new State();
            s.ID = new Guid(ddlBillToState.SelectedItem.Value);
            s.Abbreviation = (string.IsNullOrWhiteSpace(ddlBillToState.SelectedItem.Text) ? string.Empty : ddlBillToState.SelectedItem.Text);

            //address
            address = new Address();
            address.AddressBlock = txtBillToStreet.Text;
            address.City = txtBillToCity.Text;
            address.PostCode = txtBillToZip.Text;
            address.State = s;

            billto.Address = address;

            //phone number
            phone = new Phone();
            phone.Number = txtBillToPhone.Text;
            phone.Extension = txtBillToExtension.Text;

            billto.Phone = phone;

            //fax            
            phone = new Phone();
            phone.Number = txtBillToFax.Text;
            phone.PhoneType = phoneType;
            billto.Phones.Add(phone);

            //email            
            email = new Email();
            email.EmailAddress = txtBillToEmail.Text;

            billto.EmailAddress = email;

            job.BillTo = billto;
            //end bill to

            return job;
        }

        protected void btnLocationReset_Click(object sender, EventArgs e)
        {
            SearchGridView(grvLocationSearch, string.Empty);
        }
    }
}